package com.example.springbootdemo.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.exception.BusinessResponseEnum;
import com.example.springbootdemo.bean.response.ResponseInfo;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户虽然登录了，但是权限不够访问某些资源，这时候就需要AccessDeniedHandler来处理了
 * @author hh
 * @date 2022/1/27
 */
@Component
public class RequestAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(ResponseInfo.fail(BusinessResponseEnum.ACCESS_DENIED)));
    }

}
